package org.fastiot.data

import grails.converters.JSON
import grails.testing.gorm.DomainUnitTest
import spock.lang.Specification

class AggregationRulesSpec extends Specification implements DomainUnitTest<AggregationRules> {

    def setup() {
    }

    def cleanup() {
    }

    void "Test a valid properties"() {
        given:
        def instance = new AggregationRules(
                dataSet: dataSet, bindHexPacketCode: bindHexPacketCode, field1: field1, field2: field2, field3: field3
        )

        when:
        instance.save(flush: true)

        then:
        !instance.hasErrors()

        when:
        def realValueOfField1 = instance.field1.getFieldValueByPath(sourceContainsFields)
        def realValueOfField2 = instance.field2.getFieldValueByPath(sourceContainsFields)
        def realValueOfField3 = instance.field3.getFieldValueByPathAndEnum(sourceContainsFields)

        then:
        realValueOfField1 == expectedValueOfField1
        realValueOfField2 == expectedValueOfField2
        realValueOfField3 == expectedValueOfField3

        where:
        dataSet << [new DataSet(code: "ds1", name: "数据集1", scene: DataSet.AggregateScene.TimeSharing).save(flush: true)]
        bindHexPacketCode << ["0900"]
        field1 << [new AggregationRules.FieldDescription(code: "Power1", name: "功率1", path: "x.MotorList[0].Power")]
        field2 << [new AggregationRules.FieldDescription(code: "Torque2", name: "扭矩2", path: "x.MotorList[1].Torque")]
        field3 << [new AggregationRules.FieldDescription(code: "Status2", name: "状态2", path: "x.MotorList[1].Status", enumRange: "{'0':'关闭','1':'开启'}")]
        sourceContainsFields << [JSON.parse("{'MotorCount':2,MotorList:[{'SN':0,'Torque':155, 'Power':352, 'Status':0},{'SN':1,'Torque':168, 'Power':426, 'Status':1}]}")]
        expectedValueOfField1 << [352]
        expectedValueOfField2 << [168]
        expectedValueOfField3 << ["开启"]
    }
}
